import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, InputNumber, message, Space, Popconfirm, Select, Card, Tag, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, WalletOutlined, DisconnectOutlined, ReloadOutlined } from '@ant-design/icons';
import { ethers } from 'ethers';
import { 
  NETWORKS, 
  CONTRACT_ADDRESSES, 
  BOOK1155_ABI, 
  getNetworkConfig, 
  getContractAddresses, 
  isNetworkConfigured,
  getExplorerLink 
} from '../config/contracts';

export default function BookManagement() {
  const [books, setBooks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingBook, setEditingBook] = useState(null);
  const [form] = Form.useForm();
  
  // 区块链相关状态
  const [wallet, setWallet] = useState(null);
  const [currentNetwork, setCurrentNetwork] = useState('hardhat');
  const [contracts, setContracts] = useState(null);
  const [networkConnected, setNetworkConnected] = useState(false);

  // 初始化
  useEffect(() => {
    loadBooksFromContract();
  }, [contracts]);

  // 连接钱包
  const connectWallet = async () => {
    if (typeof window.ethereum !== 'undefined') {
      try {
        await window.ethereum.request({ method: 'eth_requestAccounts' });
        const provider = new ethers.providers.Web3Provider(window.ethereum);
        const signer = provider.getSigner();
        const address = await signer.getAddress();
        
        setWallet({ provider, signer, address });
        message.success('钱包连接成功！');
        
        // 连接合约
        await connectToNetwork(currentNetwork, provider, signer);
        
      } catch (error) {
        message.error('钱包连接失败: ' + error.message);
      }
    } else {
      message.error('请安装 MetaMask 钱包');
    }
  };

  // 连接到指定网络
  const connectToNetwork = async (networkKey, provider, signer) => {
    try {
      const network = getNetworkConfig(networkKey);
      const addresses = getContractAddresses(networkKey);
      
      if (!isNetworkConfigured(networkKey)) {
        message.warning(`${network.name} 网络的合约地址未配置`);
        return;
      }

      // 检查当前网络
      const currentChainId = await provider.getNetwork().then(n => n.chainId);
      if (currentChainId !== network.chainId) {
        if (networkKey !== 'hardhat') {
          await switchNetwork(network.chainId);
        } else {
          message.warning('请手动切换到本地 Hardhat 网络 (RPC: http://localhost:8545, Chain ID: 31337)');
          return;
        }
      }

      // 连接合约
      const book1155Contract = new ethers.Contract(addresses.BOOK1155, BOOK1155_ABI, signer);
      
      setContracts({
        book1155: book1155Contract
      });
      setNetworkConnected(true);
      
      message.success(`已连接到 ${network.name}`);
      
    } catch (error) {
      message.error('网络连接失败: ' + error.message);
      setNetworkConnected(false);
    }
  };

  // 切换网络
  const switchNetwork = async (chainId) => {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: ethers.utils.hexValue(chainId) }],
      });
    } catch (error) {
      message.error('网络切换失败: ' + error.message);
      throw error;
    }
  };

  // 网络切换处理
  const handleNetworkChange = async (networkKey) => {
    setCurrentNetwork(networkKey);
    if (wallet) {
      await connectToNetwork(networkKey, wallet.provider, wallet.signer);
    }
  };

  // 从合约加载图书数据
  const loadBooksFromContract = async () => {
    if (!contracts) return;
    
    setLoading(true);
    try {
      const book1155 = contracts.book1155;
      
      // 获取所有已铸造的图书ID
      const bookIds = await book1155.getAllMintedBookIds();
      
      const booksData = [];
      for (let i = 0; i < bookIds.length; i++) {
        const id = bookIds[i];
        const tokenInfo = await book1155.getNormalTokenInfo(id);
        const totalAmount = await book1155.getIdAmount(id);
        const saleAmount = await book1155.getIdSaleAmount(id);
        
        booksData.push({
          id: id.toNumber(),
          isbn: tokenInfo.ISBN,
          title: tokenInfo.ISBN, // 临时用ISBN作为标题
          author: '链上作者', // 可以从IPFS元数据获取
          price: parseFloat(ethers.utils.formatEther(tokenInfo.price)),
          amount: totalAmount.toNumber(),
          soldAmount: totalAmount.toNumber() - saleAmount.toNumber(),
          status: saleAmount.toNumber() > 0 ? '已上架' : '未上架',
          imageURI: tokenInfo.imageURI,
          mintTimestamp: new Date(tokenInfo.mintTimestamp.toNumber() * 1000).toLocaleString(),
          minter: tokenInfo.minter
        });
      }
      
      setBooks(booksData);
      message.success(`从合约加载了 ${booksData.length} 本图书`);
      
    } catch (error) {
      console.error('从合约加载数据失败:', error);
      message.error('从合约加载数据失败: ' + error.message);
      
      // 如果合约连接失败，显示示例数据
      setBooks([
        {
          id: 1,
          isbn: '978-0123456789',
          title: '区块链技术指南',
          author: '张三',
          price: 0.1,
          amount: 100,
          soldAmount: 25,
          status: '已上架'
        }
      ]);
    } finally {
      setLoading(false);
    }
  };

  // 铸造新图书到合约
  const mintBookToContract = async (bookData) => {
    if (!contracts) {
      message.error('请先连接到区块链网络');
      return false;
    }

    try {
      const book1155 = contracts.book1155;
      
      const tx = await book1155.mint(
        bookData.id || Date.now(), // 使用时间戳作为ID
        bookData.isbn,
        bookData.amount,
        bookData.imageURI || '',
        ethers.utils.parseEther(bookData.price.toString()),
        bookData.contentHash || 'QmDefaultContentHash',
        bookData.metadataHash || 'QmDefaultMetadataHash',
        bookData.previewHash || 'QmDefaultPreviewHash',
        false, // isEncrypted
        '' // encryptionKey
      );
      
      message.loading('交易确认中...', 0);
      await tx.wait();
      message.destroy();
      
      return true;
    } catch (error) {
      console.error('铸造失败:', error);
      message.error('铸造失败: ' + error.message);
      return false;
    }
  };

  // 表格列定义 (增加区块链相关信息)
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: 'ISBN',
      dataIndex: 'isbn',
      key: 'isbn',
      width: 150,
    },
    {
      title: '书名',
      dataIndex: 'title',
      key: 'title',
      width: 200,
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 120,
    },
    {
      title: '价格 (ETH)',
      dataIndex: 'price',
      key: 'price',
      width: 120,
      render: (price) => price.toFixed(3),
    },
    {
      title: '总数量',
      dataIndex: 'amount',
      key: 'amount',
      width: 100,
    },
    {
      title: '已售',
      dataIndex: 'soldAmount',
      key: 'soldAmount',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === '已上架' ? 'green' : 'orange'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '铸造时间',
      dataIndex: 'mintTimestamp',
      key: 'mintTimestamp',
      width: 150,
      render: (time) => time || '未知',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="primary" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  // 新增图书
  const handleAdd = () => {
    setEditingBook(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 编辑图书
  const handleEdit = (book) => {
    setEditingBook(book);
    form.setFieldsValue(book);
    setModalVisible(true);
  };

  // 提交表单
  const handleSubmit = async (values) => {
    setLoading(true);
    
    try {
      if (editingBook) {
        // 编辑 - 目前只更新本地状态，链上数据不可更改
        setBooks(books.map(book => 
          book.id === editingBook.id 
            ? { ...book, ...values }
            : book
        ));
        message.success('本地编辑成功（链上数据不可更改）');
      } else {
        // 新增 - 铸造到合约
        const success = await mintBookToContract(values);
        if (success) {
          message.success('图书铸造成功！');
          // 重新加载数据
          setTimeout(() => loadBooksFromContract(), 2000);
        }
      }
      
      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 网络状态卡片 */}
      <Card style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h2 style={{ margin: 0 }}>图书NFT管理系统</h2>
            <p style={{ margin: '8px 0 0 0', color: '#666' }}>
              基于区块链的图书NFT铸造和管理平台
            </p>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            {/* 网络选择 */}
            <div>
              <span style={{ marginRight: '8px' }}>网络:</span>
              <Select
                value={currentNetwork}
                onChange={handleNetworkChange}
                style={{ width: 150 }}
                disabled={!wallet}
              >
                {Object.entries(NETWORKS).map(([key, network]) => (
                  <Select.Option key={key} value={key}>
                    <Tag color={network.color} style={{ margin: 0 }}>
                      {network.tag}
                    </Tag>
                    {network.name}
                  </Select.Option>
                ))}
              </Select>
            </div>

            {/* 连接状态 */}
            <div>
              {networkConnected ? (
                <Tag color="green">已连接</Tag>
              ) : (
                <Tag color="red">未连接</Tag>
              )}
            </div>

            {/* 钱包地址 */}
            {wallet && (
              <Tooltip title={wallet.address}>
                <Tag>{wallet.address.slice(0, 6)}...{wallet.address.slice(-4)}</Tag>
              </Tooltip>
            )}

            {/* 连接/刷新按钮 */}
            <Space>
              {!wallet ? (
                <Button 
                  type="primary" 
                  icon={<WalletOutlined />}
                  onClick={connectWallet}
                >
                  连接钱包
                </Button>
              ) : (
                <Button 
                  icon={<ReloadOutlined />}
                  onClick={loadBooksFromContract}
                  loading={loading}
                >
                  刷新数据
                </Button>
              )}
              
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleAdd}
                disabled={!networkConnected}
              >
                铸造图书
              </Button>
            </Space>
          </div>
        </div>
      </Card>

      {/* 数据表格 */}
      <Table 
        columns={columns} 
        dataSource={books} 
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      {/* 新增/编辑模态框 */}
      <Modal
        title={editingBook ? '编辑图书信息' : '铸造新图书NFT'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="ISBN"
            name="isbn"
            rules={[
              { required: true, message: '请输入ISBN' },
              { pattern: /^978-\d{10}$/, message: 'ISBN格式应为：978-xxxxxxxxxx' }
            ]}
          >
            <Input placeholder="例如：978-0123456789" />
          </Form.Item>

          <Form.Item
            label="书名"
            name="title"
            rules={[{ required: true, message: '请输入书名' }]}
          >
            <Input placeholder="请输入书名" />
          </Form.Item>

          <Form.Item
            label="作者"
            name="author"
            rules={[{ required: true, message: '请输入作者' }]}
          >
            <Input placeholder="请输入作者" />
          </Form.Item>

          <Form.Item
            label="价格 (ETH)"
            name="price"
            rules={[
              { required: true, message: '请输入价格' },
              { type: 'number', min: 0.001, message: '价格不能小于0.001 ETH' }
            ]}
          >
            <InputNumber 
              min={0.001} 
              step={0.001} 
              style={{ width: '100%' }}
              placeholder="请输入价格"
            />
          </Form.Item>

          <Form.Item
            label="发行数量"
            name="amount"
            rules={[
              { required: true, message: '请输入发行数量' },
              { type: 'number', min: 1, message: '发行数量不能小于1' }
            ]}
          >
            <InputNumber 
              min={1} 
              style={{ width: '100%' }}
              placeholder="请输入发行数量"
            />
          </Form.Item>

          <Form.Item
            label="封面图片URL"
            name="imageURI"
          >
            <Input placeholder="请输入图片URL (可选)" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                disabled={!networkConnected && !editingBook}
              >
                {editingBook ? '更新' : '铸造到区块链'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
} 